package com.elock.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.elock.base.core.ExcelView;
import com.elock.base.core.Page;
import com.elock.base.core.Pageable;
import com.elock.base.core.controller.BaseController;
import com.elock.base.core.controller.ResultMsg;
import com.elock.base.core.util.JsonUtils;
import com.elock.base.core.util.WebUtils;
import com.elock.service.CarSaleOrgService;
import com.elock.service.CarService;
import com.elock.service.ElockCarService;
import com.elock.service.TerminalMessageEventService;
import com.elock.util.SystemConfig;

/**
 * Controller - 事件监控列表
 * @author 仁德
 */
@Controller("messageEventMonitorController")
@RequestMapping("/message_event_monitor")
public class MessageEventMonitorController extends BaseController {

	@Resource(name = "carServiceImpl")
	private CarService carService;
	@Resource(name = "elockCarServiceImpl")
	private ElockCarService elockCarService;
	@Resource(name = "carSaleOrgServiceImpl")
	private CarSaleOrgService carSaleOrgService;
	@Resource(name = "terminalMessageEventServiceImpl")
	private TerminalMessageEventService terminalMessageEventService;

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list_tb", method = RequestMethod.GET)
	public String list_tb(ModelMap model) {

		return "/message_event_monitor/list_tb";
	}

	/**
	 * 列表
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public String list(Pageable pageable, ModelMap model) {

		return "/message_event_monitor/list";
	}

	/**
	 * 列表数据
	 */
	@RequestMapping(value = "/list_data", method = RequestMethod.POST)
	public @ResponseBody ResultMsg list_data(String plateNum, String terminalNum,
			String elockNum, Long saleOrgId, String startTime, String endTime,
			Pageable pageable, ModelMap model) {

		Page<Map<String, Object>> pageMap = terminalMessageEventService.findPage(null,
				null,
				null,
				plateNum,
				terminalNum,
				elockNum,
				saleOrgId,
				startTime,
				endTime,
				pageable);
		String jsonPage = JsonUtils.toJson(pageMap);

		return success(jsonPage);
	}

	@RequestMapping(value = "/to_condition_export", method = RequestMethod.POST)
	public @ResponseBody List<Map<String, Object>> toConditionExport(String plateNum,
			String terminalNum, String elockNum, Long saleOrgId, String startTime,
			String endTime, Pageable pageable, ModelMap model) {

		Integer size = terminalMessageEventService.countTerminalMessageEvent(null,
				null,
				null,
				plateNum,
				terminalNum,
				elockNum,
				saleOrgId,
				startTime,
				endTime,
				pageable,
				null,
				null);
		List<Map<String, Object>> lists = new ArrayList<Map<String, Object>>();
		Map<String, Integer> segments = getSegment();
		int stage = segments.get("segment");
		int page_size = segments.get("size");
		for (int i = 0; i < stage; i++) {
			Map<String, Object> map = new HashMap<String, Object>();
			int total = i * page_size;
			if (size == 0) {
				map.put("data", "0-0");
			}
			else if ((size - total) <= page_size) {
				map.put("data", (total + 1) + "-" + size);
			}
			else {
				map.put("data", (total + 1) + "-" + (i + 1) * page_size);
			}
			lists.add(map);
			if ((size - total) <= page_size) {
				break;
			}
		}
		return lists;
	}

	/**
	 * 条件导出
	 * @return
	 */
	@RequestMapping(value = "/condition_export", method = RequestMethod.GET)
	public ModelAndView conditionExport(String plateNum, String terminalNum,
			String elockNum, Long saleOrgId, String startTime, String endTime,
			Pageable pageable, ModelMap model, Integer page) {

		Map<String, Integer> segments = getSegment();
		int size = segments.get("size");
		List<Map<String, Object>> data = terminalMessageEventService
				.findTerminalMessageEventList(null,
						null,
						null,
						plateNum,
						terminalNum,
						elockNum,
						saleOrgId,
						startTime,
						endTime,
						pageable,
						page,
						size);
		return this.getModelAndView(data, model);

	}

	public ModelAndView getModelAndView(List<Map<String, Object>> data, ModelMap model) {
		for (Map<String, Object> str : data) {
			if (str.get("status") != null) {
				Integer status = (Integer) str.get("status");
				if (status == 1) {
					str.put("status_str", "开锁");
				}
				else {
					str.put("status_str", "锁定");
				}
			}
			String berth = "";
			if (str.get("berth") != null) {
				berth = str.get("berth").toString();
			}
			String position = "";
			if (str.get("position") != null) {
				position = str.get("position").toString();
			}
			str.put("berth_position", berth + "," + position);
			if (str.get("altitude") != null) {
				str.put("altitude",
						new BigDecimal(str.get("altitude").toString()).setScale(2,
								BigDecimal.ROUND_HALF_UP));
			}
			if (str.get("speed") != null) {
				str.put("speed",
						new BigDecimal(str.get("speed").toString()).setScale(2,
								BigDecimal.ROUND_HALF_UP));
			}
//			if (str.get("create_date") != null) {
//
//				String create_date = DateUtil.convert((Date) str.get("create_date"));
//				if (create_date.length() > 19) {
//					create_date = create_date.substring(0, 19);
//				}
//				str.put("create_date", create_date);
//			}
//			if (str.get("is_enabled") != null && (Boolean) str.get("is_enabled")) {
//				str.put("is_enabled", "是");
//			}
//			else {
//				str.put("is_enabled", "否");
//			}
		}

		//设置导出表格名
		String filename = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + ".xls";
		//设置标题
		String[] header = { "终端设备编号",
				"事件信息",
				"状态信息描述",
				"报警信息",
				"事件发生时间",
				"操作人",
				"任务单流水号",
				"车牌号",
				"锁编号",
				"舱位",
				"经度",
				"纬度",
				"基站定位数据",
				"电压",
				"海拔高度",
				"速度",
				"方向",
				"GPS时间",
				"备注" };
		//设置单元格取值
		String[] properties = { "terminal_num",
				"event_message",
				"status_desc",
				"warning_message",
				"event_time",
				"processor",
				"task_sn",
				"car_number",
				"elock_num",
				"position",
				"longitude",
				"latitude",
				"jzdw",
				"vol",
				"altitude",
				"speed",
				"direction",
				"gps_time",
				"remark" };

		return new ModelAndView(
				new ExcelView(filename, null, properties, header, null, null, data, null),
				model);
	}

	private Map<String, Integer> getSegment() {
		HashMap<String, Integer> map = new HashMap<String, Integer>();
		try {
			String value = SystemConfig.getConfig("SegmentExportConfig",
					WebUtils.getCurrentCompanyInfoId());
			String[] values = value.split(",");
			map.put("segment", Integer.parseInt(values[0]));
			map.put("size", Integer.parseInt(values[1]));
		}
		catch (Exception e) {
			map.put("segment", 10);
			map.put("size", 1000);
		}
		return map;
	}
}
